package com.mo.core.intercept;

import io.jsonwebtoken.JwtException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mo.common.exception.BizExceptionEnum;
import com.mo.config.properties.JwtProperties;
import com.mo.core.base.tips.ErrorTip;
import com.mo.core.util.JwtTokenUtil;
import com.mo.core.util.RenderUtil;

/**
 * 对客户端请求的jwt token验证过滤器
 *
 * @author chenxiaodong
 * @Date 2017/8/24 14:04
 */
public class HessianInterceptor extends HandlerInterceptorAdapter  {

	public HessianInterceptor(JwtProperties jwtproperties){
		this.jwtProperties = jwtproperties;
	}
//	@Autowired
	private JwtProperties jwtProperties;

	@Override
	 public boolean preHandle(
			 HttpServletRequest request, 
			 HttpServletResponse httpServletResponse, 
			 Object handler) throws Exception { 
		System.out.println(request.getServletPath());
		if (request.getServletPath().indexOf("hessian")>0) {
			final String requestHeader = request.getHeader(jwtProperties
					.getHeader());
			String authToken = null;
			if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
				authToken = requestHeader.substring(7);
				// 验证token是否过期
				try {
					boolean flag = JwtTokenUtil.isTokenExpired(authToken,jwtProperties.getSecret());
					if (flag) {
						RenderUtil.renderJson(httpServletResponse, new ErrorTip(
								BizExceptionEnum.TOKEN_EXPIRED.getCode(),
								BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
						return false;
					}
				} catch (JwtException e) {
					// 有异常就是token解析失败
					RenderUtil.renderJson(httpServletResponse, new ErrorTip(
							BizExceptionEnum.TOKEN_ERROR.getCode(),
							BizExceptionEnum.TOKEN_ERROR.getMessage()));
					return false;
				}
			} else {
				// header没有带Bearer字段
				RenderUtil.renderJson(httpServletResponse, new ErrorTip(
						BizExceptionEnum.TOKEN_ERROR.getCode(),
						BizExceptionEnum.TOKEN_ERROR.getMessage()));
				return false;
			}
		}else{
			return false;
		}
		return true;
	}

}
